package com.example.poemtest.index.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.poemtest.R;
import com.example.poemtest.entity.PoetryInfoBean;
import com.example.poemtest.entity.PropInfoBean;
import com.example.poemtest.index.entity.Poetry;
import com.example.poemtest.index.entity.WritePoetry;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.github.mthli.knife.KnifeText;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 灵感创作页面
 */
public class WritePoetryActivity extends AppCompatActivity {

    private KnifeText knife;
    private EditText editText;
    private Button button;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    //解析json文件流
//                    PropInfoBean propInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PropInfoBean.class);
//                    List<PropInfoBean.PropInfo> list = propInfoBean.getData();
//                    if (Constant.myPropList.size() != 0) {
//                        Constant.myPropList.clear();
//                    }
//                    for (PropInfoBean.PropInfo propInfo : list) {
//                        Constant.myPropList.add(propInfo);
//                    }
//                    for (PropInfoBean.PropInfo propInfo : Constant.myPropList) {
//                        Log.e("收到的道具数据",propInfo.toString());
//                    }
                } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtil.getInstance().fullScreen(this,true);
        setContentView(R.layout.activity_write_poetry);
        knife = (KnifeText) findViewById(R.id.knife);
        // ImageGetter coming soon...
//        knife.fromHtml(EXAMPLE);
        knife.setSelection(knife.getEditableText().length());

        setupBold();
        setupItalic();
        setupUnderline();
        setupStrikethrough();
        setupBullet();
        setupQuote();
        setupLink();
        setupClear();
        //题目
        editText = findViewById(R.id.poetry_user_title);
        //保存按钮
        button = findViewById(R.id.btn_baocun);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("题目",editText.getText().toString());
                Log.e("内容",knife.getEditableText().toString());
                //将获取到的信息存储在类中
                WritePoetry writePoetry = new WritePoetry();
                writePoetry.setPoetryTitle(editText.getText().toString());
                writePoetry.setPoetryAuther("欲饮一壶酒");
                writePoetry.setPoetryContent(knife.getEditableText().toString());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                Date date = new Date(System.currentTimeMillis());
                writePoetry.setWriteDate(date);
                writePoetry.setReviseDate(date);
                Log.e("诗词",writePoetry.toString());
                //包装成一个对象，发送到后端，存储到数据库
//                Poetry poetry = new Poetry();
//                poetry.setPoetry_name(editText.getText().toString());
//                poetry.setPoetry_author("欲饮一壶酒");
//                poetry.setPoetry_content(knife.getEditableText().toString());
//                poetry.setCreatDate(date);
//                poetry.setReviseDate(date);
                //加入到用户自己写诗的数组中去
//                Constant.writePoetryList.add(poetry);

                PoetryInfoBean.PoetryInfo poetryInfo = new PoetryInfoBean.PoetryInfo();
                poetryInfo.setPoetryTitle(editText.getText().toString());
                poetryInfo.setPoetryAuthor(Constant.userName);
                poetryInfo.setPoetryContent(knife.getEditableText().toString());
                getCoon(poetryInfo);
//                Log.e("写诗",poetry.toString());
                finish();
            }
        });

    }
    private void setupBold() {
        ImageButton bold = (ImageButton) findViewById(R.id.bold);

        bold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.bold(!knife.contains(KnifeText.FORMAT_BOLD));
            }
        });

        bold.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_bold, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupItalic() {
        ImageButton italic = (ImageButton) findViewById(R.id.italic);

        italic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.italic(!knife.contains(KnifeText.FORMAT_ITALIC));
            }
        });

        italic.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_italic, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupUnderline() {
        ImageButton underline = (ImageButton) findViewById(R.id.underline);

        underline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.underline(!knife.contains(KnifeText.FORMAT_UNDERLINED));
            }
        });

        underline.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_underline, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupStrikethrough() {
        ImageButton strikethrough = (ImageButton) findViewById(R.id.strikethrough);

        strikethrough.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.strikethrough(!knife.contains(KnifeText.FORMAT_STRIKETHROUGH));
            }
        });

        strikethrough.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_strikethrough, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupBullet() {
        ImageButton bullet = (ImageButton) findViewById(R.id.bullet);

        bullet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.bullet(!knife.contains(KnifeText.FORMAT_BULLET));
            }
        });


        bullet.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_bullet, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupQuote() {
        ImageButton quote = (ImageButton) findViewById(R.id.quote);

        quote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.quote(!knife.contains(KnifeText.FORMAT_QUOTE));
            }
        });

        quote.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_quote, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupLink() {
        ImageButton link = (ImageButton) findViewById(R.id.link);

        link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLinkDialog();
            }
        });

        link.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_insert_link, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void setupClear() {
        ImageButton clear = (ImageButton) findViewById(R.id.clear);

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                knife.clearFormats();
            }
        });

        clear.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(WritePoetryActivity.this, R.string.toast_format_clear, Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void showLinkDialog() {
        final int start = knife.getSelectionStart();
        final int end = knife.getSelectionEnd();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);

        View view = getLayoutInflater().inflate(R.layout.dialog_link, null, false);
        final EditText editText = (EditText) view.findViewById(R.id.edit);
        builder.setView(view);
        builder.setTitle(R.string.dialog_title);

        builder.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String link = editText.getText().toString().trim();
                if (TextUtils.isEmpty(link)) {
                    return;
                }

                // When KnifeText lose focus, use this method
                knife.link(link, start, end);
            }
        });

        builder.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // DO NOTHING HERE
            }
        });

        builder.create().show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.undo:
                knife.undo();
                break;
            case R.id.redo:
                knife.redo();
                break;
            case R.id.github:
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.app_repo)));
                startActivity(intent);
                break;
            default:
                break;
        }

        return true;
    }

    /**
     * 获取网络连接,将创作好的诗存储到数据库中
     */
    private void getCoon(PoetryInfoBean.PoetryInfo poetryInfo){
        //向后端传递页面上获取的账号密码
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("poetryTitle",poetryInfo.getPoetryTitle());
            jsonObject.put("poetryAuthor",poetryInfo.getPoetryAuthor());
            jsonObject.put("poetryContent",poetryInfo.getPoetryContent());
            jsonObject.put("createByUserId",Constant.userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/poetryInfo/insertPoetryInfo")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}